<?php

namespace app\common\library\xmwechat\offiaccount;

use app\common\library\xmwechat\SingletonTrait;
use app\common\library\xmwechat\WechatService;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\OfficialAccount\Application;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use think\exception\HttpResponseException;
use think\Response;

/**
 * 素材管理
 */
class MaterialService extends WechatService
{
    protected ?Application $app;
    protected string $accessToken;

    use SingletonTrait;

    public function __construct()
    {
        parent::__construct();
        if (empty($this->offiAccountConfig['app_id']) || empty($this->offiAccountConfig['secret'])) {
            $this->result('请配置公众号appid或secret');
        }
        $this->app         = new Application([
            'app_id' => $this->offiAccountConfig['app_id'],
            'secret' => $this->offiAccountConfig['secret'],
        ]);
        $accessToken       = $this->app->getAccessToken();
        $this->accessToken = $accessToken->getToken();
    }

    /**
     * 获取素材列表 音频、视频、图片
     * @param $type
     * @return array
     * @throws TransportExceptionInterface
     * @throws ClientExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function getMaterialList($type, $page, $page_size): array
    {
        try {
            $count = $this->getMaterialCount();
            if ($type == 'voice') {
                $total_count = $count['voice_count'];
            } else if ($type == 'video') {
                $total_count = $count['video_count'];
            } else if ($type == 'image') {
                $total_count = $count['image_count'];
            } else {
                $total_count = 0;
            }
            if ($total_count == 0) {
                return [
                    'list'  => [],
                    'total' => $total_count
                ];
            }
            empty($page) || $page == 0 ? $offset = 0 : $offset = ($page - 1) * $page_size;
            // 分页获取素材
            $response = $this->app->getClient()->postJson('cgi-bin/material/batchget_material?access_token=' . $this->accessToken, [
                'type'   => $type,
                'offset' => $offset,
                'count'  => $page_size
            ]);
            if ($response->isFailed()) {
                // 出错了，处理异常
                $this->result($response->getContent());
            }
            $result = $response->getContent();
            $data   = json_decode($result, true);

            if ($type == 'voice') {
                $list = $data['item'];
                foreach ($list as $k => $v) {
                    $list[$k]['reply_content'] = json_encode([
                        'type'     => 'voice',
                        'media_id' => $v['media_id'],
                        'name'     => $v['name'],
                    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            } else if ($type == 'video') {
                $list = $data['item'];
                foreach ($list as $k => $v) {
                    $list[$k]['image']         = $v['cover_url'];
                    $list[$k]['reply_content'] = json_encode([
                        'type'        => 'video',
                        'media_id'    => $v['media_id'],
                        'name'        => $v['name'],
                        'cover_url'   => str_replace('/', '\/', $v['cover_url']),
                        'description' => $v['description'],
                        'vid'         => $v['vid']
                    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            } else if ($type == 'image') {
                $list = $data['item'];
                foreach ($list as $k => $v) {
                    $list[$k]['image']         = $v['url'];
                    $list[$k]['reply_content'] = json_encode([
                        'type'     => 'image',
                        'media_id' => $v['media_id'],
                        'name'     => $v['name'],
                        'url'      => str_replace('/', '\/', $v['url'])
                    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }
            } else {
                $list = [];
            }
            return [
                'list'  => $list,
                'total' => $total_count
            ];
        } catch (\Exception $e) {
            $this->result($e->getMessage());
        }
    }

    /**
     * 获取已发布的图文素材
     * @return array
     * @throws TransportExceptionInterface
     * @throws ClientExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function getMaterialFreePublish($page, $page_size): array
    {
        $list        = [];
        $total_count = 0;
        try {
            empty($page) || $page == 0 ? $offset = 0 : $offset = ($page - 1) * $page_size;
            $result = $this->app->getClient()->postJson('cgi-bin/freepublish/batchget?access_token=' . $this->accessToken, [
                'offset' => $offset,
                'count'  => $page_size,
            ]);
            if ($result->isFailed()) {
                $this->result($result->getContent());
            }
            $data = json_decode($result, true);
            if (!empty($data)) {
                $list = $data['item'];
                foreach ($list as $k => $v) {
                    $content                           = $v['content']['news_item'][0];
                    $list[$k]['article_id']            = $v['article_id'];
                    $list[$k]['title']                 = $content['title'];
                    $list[$k]['author']                = $content['author'];
                    $list[$k]['digest']                = $content['digest'];
                    $list[$k]['content']               = $content['content'];
                    $list[$k]['content_source_url']    = $content['content_source_url'];
                    $list[$k]['thumb_media_id']        = $content['thumb_media_id'];
                    $list[$k]['show_cover_pic']        = $content['show_cover_pic'];
                    $list[$k]['url']                   = $content['url'];
                    $list[$k]['image']                 = $content['thumb_url'];
                    $list[$k]['need_open_comment']     = $content['need_open_comment'];
                    $list[$k]['only_fans_can_comment'] = $content['only_fans_can_comment'];
                    $list[$k]['is_deleted']            = $content['is_deleted'];
                    $list[$k]['reply_content']         = json_encode([
                        'type'           => 'news',
                        'article_id'     => $v['article_id'],
                        'title'          => $content['title'],
                        'digest'         => $content['digest'],
                        'show_cover_pic' => str_replace('/', '\/', $content['show_cover_pic']),
                        'url'            => str_replace('/', '\/', $content['url'])
                    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                }

                $total_count = $data['total_count'];
            }
        } catch (\Exception $e) {
            $this->result($e->getMessage());
        }
        return [
            'list'  => $list,
            'total' => $total_count
        ];
    }

    /**
     * 获取素材总数量（音频、视频、图片）
     * @return array
     * @throws \Exception|TransportExceptionInterface
     * @author jsjxsz <QQ:1365962177>
     */
    public function getMaterialCount(): array
    {
        try {
            // 获取素材总数
            $materialcount = $this->app->getClient()->get('cgi-bin/material/get_materialcount?access_token=' . $this->accessToken);
            if ($materialcount->isFailed()) {
                $this->result($materialcount->getContent());
            }
            return json_decode($materialcount->getContent(), true);
        } catch (\Exception $e) {
            $this->result($e->getMessage());
        }
    }

    /**
     * 根据media_id获取视频素材、只能获取视频素材，音频、图片素材微信已不再返回
     * @param $media_id
     * @throws ClientExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     * @throws TransportExceptionInterface
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function getMaterialByMediaId($media_id)
    {
        try {
            //获取素材总数
            $result = $this->app->getClient()->postJson('cgi-bin/material/get_material?access_token=' . $this->accessToken, [
                'media_id' => $media_id
            ]);
            if ($result->isFailed()) {
                $this->result($result->getContent());
            }
            return json_decode($result->getContent(), true);
        } catch (\Exception $e) {
            $this->result($e->getMessage());
        }
    }

    /**
     * 根据article_id获取图文素材
     * 接口每日调用上线100次
     * @param $article_id
     * @throws ClientExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     * @throws TransportExceptionInterface
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function getMaterialByArticleId($article_id)
    {
        try {
            //获取素材总数
            $result = $this->app->getClient()->postJson('cgi-bin/freepublish/getarticle?access_token=' . $this->accessToken, [
                'article_id' => $article_id
            ]);
            if ($result->isFailed()) {
                $this->result($result->getContent());
            }
            $result = json_decode($result->getContent(), true);
            return $result['news_item'][0];
        } catch (\Exception $e) {
            $this->result($e->getMessage());
        }
    }

}